package com.zg.shop.product;

import java.util.Date;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.zg.shop.utils.PageHibernateCallback;

public class ProductDao extends HibernateDaoSupport {

	public List<Product> findHot() {
		DetachedCriteria critera = DetachedCriteria.forClass(Product.class);
		critera.add(Restrictions.eq("is_hot", 1));
		return this.getHibernateTemplate().findByCriteria(critera, 0, 10);
	}

	public List<Product> findNew() {
		List<Product> products = this.getHibernateTemplate()
				.executeFind(new PageHibernateCallback<Product>("from Product order by pdate desc", null, 0, 10));
		return products;
	}

	public Integer findCountByCid(Integer cid) {
		List<Long> count = this.getHibernateTemplate().find(
				"select count(*) from Product p , CategorySecond cs where p.categorySecond = cs and cs.category.cid = ?",
				cid);
		System.out.println("=============" + count.get(0).intValue());
		return count.get(0).intValue();
	}

	public List<Product> findByPage(Integer cid, int begin, int limit) {
		String hql = "select p from  Product p, CategorySecond cs where p.categorySecond = cs and cs.category.cid = ?";
		List<Product> products = this.getHibernateTemplate()
				.executeFind(new PageHibernateCallback<Product>(hql, new Object[] { cid }, begin, limit));
		return products;
	}

	public Product findProductInfoByPid(Integer pid) {
		Product product = this.getHibernateTemplate().get(Product.class, pid);
		return product;
	}

	public Integer findCountByCsid(Integer csid) {
		String hql = "select count(*) from Product p join p.categorySecond cs where cs.csid=?";
		List<Long> list = this.getHibernateTemplate().find(hql, csid);
		return list.get(0).intValue();
	}

	public List<Product> findPageByCsid(Integer csid, int begin, int limit) {
		String hql = "select p from Product p join p.categorySecond cs where cs.csid = ?";
		List<Product> products = this.getHibernateTemplate()
				.executeFind(new PageHibernateCallback<Product>(hql, new Object[] { csid }, begin, limit));
		return products;
	}

	public Integer findCount() {
		String hql = "select count(*) from Product";
		List<Long> list = this.getHibernateTemplate().find(hql);
		if (list.size() > 0) {
			return list.get(0).intValue();
		} else {
			return null;
		}
	}

	public List<Product> findByPage(int begin, int climit) {
		String hql = "from Product";
		List<Product> products = this.getHibernateTemplate()
				.executeFind(new PageHibernateCallback<Product>(hql, null, begin, climit));
		if (products.size() > 0) {
			return products;
		}else{
			return null;
		}
	}

	public void save(Product product) {
		this.getHibernateTemplate().save(product);
	}
}
